package xxy.com.yangproject.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.NavDestination;
import androidx.navigation.NavGraph;
import androidx.navigation.NavOptions;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.material.bottomnavigation.BottomNavigationItemView;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.lang.ref.WeakReference;
import java.util.WeakHashMap;

import xxy.com.yangproject.R;
import xxy.com.yangproject.global.Constant;
import xxy.com.yangproject.model.LoginBean;

public class NavigationSecFragment extends Fragment {

    private NavController navController;
    private Context mContext;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_navigation_sec, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mContext = getContext();
        ImageView imageView = view.findViewById(R.id.imageView3);
        BottomNavigationView navView = view.findViewById(R.id.nav_view);
        navController = Navigation.findNavController(view);

        imageView.setOnClickListener(v -> {
//            navController.popBackStack();
            navController.navigate(R.id.action_sec_navigation_to_first_navigation);
        });

        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(R.id.navigation_home, R.id.navigation_course, R.id.navigation_expand, R.id.navigation_us).build();
        NavigationUI.setupActionBarWithNavController((AppCompatActivity) getContext(), navController,appBarConfiguration);
        initSomeUI(navView);

//        Bundle bundle = new Bundle();
//        bundle.putString("testData", "hahaha");
//        Navigation.findNavController(view).navigate(R.id.action_sec_navigation_to_first_navigation, bundle);
    }

    //1.底部栏注册监听   2.navController注册监听
    private void initSomeUI(BottomNavigationView bottomNavigationView) {
        //1.初始化 2.点击事件（切换页面）
        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            if (bottomNavigationView.getSelectedItemId() == item.getItemId()) {   //重复点击则返回
                return true;
            }
            ToastUtils.showShort("item.getOrder()" + item.getOrder() + "\n" + "");
            return onNavDestinationSelected(item, navController);     //切换菜单项的动画
        });
        WeakReference<BottomNavigationView> weakReference = new WeakReference<>(bottomNavigationView);   //

        navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {      //添加目的地改变监听，和底部导航栏联动
            @Override
            public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
                BottomNavigationView view = weakReference.get();          //得到底部导航栏
                if (view == null) {
                    navController.removeOnDestinationChangedListener(this);   //及时清除监听
                    return;
                }

                Menu menu = view.getMenu();
                for (int h = 0, size = menu.size(); h < size; h++) {    //给menu设置点击
                    MenuItem item = menu.getItem(h);
                    if (matchDestination(destination, item.getItemId())) {
                        item.setChecked(true);
                    }
                }
            }
        });

    }

    private static boolean matchDestination(@NonNull NavDestination destination,
                                            @IdRes int destId) {
        NavDestination currentDestination = destination;
        while (currentDestination.getId() != destId && currentDestination.getParent() != null) {
            currentDestination = currentDestination.getParent();
        }

        return currentDestination.getId() == destId;
    }

    protected boolean onNavDestinationSelected(MenuItem item, NavController navController){
        NavOptions.Builder builder = new NavOptions.Builder().setPopExitAnim(R.anim.nav_default_pop_exit_anim).setPopEnterAnim(R.anim.nav_default_pop_enter_anim).setExitAnim(R.anim.nav_default_exit_anim).setEnterAnim(R.anim.nav_default_enter_anim);   //菜单动画
        int count;
        if ((item.getOrder() & Menu.CATEGORY_SECONDARY) == 0) {       // ?
            builder.setPopUpTo(count = findStartDestination(navController.getGraph()).getId(), false);      //菜单弹出返回栈里指定页面上的所有页面
            LogUtils.eTag(Constant.TAG_NAV, "findStartDestination(navController.getGraph()).getId() :   " + count);
        }

        try {
            navController.navigate(item.getItemId(), null, builder.build());   //跳转
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }

    private NavDestination findStartDestination(NavGraph graph) {
        NavDestination startDestination = graph;
        while (startDestination instanceof NavGraph) {
            NavGraph parent = (NavGraph) startDestination;
            startDestination = parent.findNode(parent.getStartDestination());
        }
        return startDestination;
    }
}
